package org.geeks.gsredisson.aop;

import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.redisson.api.RBucket;
import org.redisson.api.RedissonClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import java.util.concurrent.TimeUnit;

@Slf4j
@Aspect
@Component
public class DuplicateAspect {

  @Autowired private RedissonClient redissonClient;

  @Before("execution(* org.geeks.gsredisson.api.HelloApi.*(..))")
  public void before() throws Throwable {
    HttpServletRequest request =
        ((ServletRequestAttributes) RequestContextHolder.currentRequestAttributes()).getRequest();

    String token = request.getHeader("token");

    RBucket<Integer> rBucket = redissonClient.getBucket(token);

    if (!rBucket.trySet(0, 4, TimeUnit.MINUTES)) {
      throw new Exception("Duplicate request");
    }
  }
}
